shell 自定义变量

        在 shell 脚本中使用变量显得脚本更加专业更像是一门语言,变量的作用当然不是为了专业。比如写了有一个长达1000行的 shell 脚本,并且脚本中出现了某一个命令或者路径几百次,如果突然发现不对,想换一下,那不是要更改几百次。当然可以用批量替换的命令,但是也很麻烦,并且脚本显得臃肿。变量的作用就是用来解决这个问题。

1
2
[root@192 ~]# cd /usr/local/sbin/
[root@192 sbin]# vim variable.sh

        加入内容

1
2
3
4
5
6
7
8
#!/bin/bash
#In this script we will use variables.
d=`date +%H:%M:%S`
echo "The script degin at $d."
echo "Now we'll sleep 2 seconds."
sleep 2
d1=`date +%H:%M:%S`
echo "The script end at $d1."

        脚本中使用到了反引号,单引号的作用是执行命令。‘d’ 和 ‘d1’ 在脚本中作为变量出现。定义变量的格式为: 变量名=变量的值,当在脚本中引用变量时需要加上 ‘$’ 符号。

        脚本执行结果:

1
[root@192 sbin]# sh variable.sh

数学运算

        在 shell 中经常会用到数学运算,下面示例脚本用来计算两个数字的和。

1
[root@192 sbin]# vim sum.sh

        写入内容

1
2
3
4
5
6
7
#!/bin/bash
#For get the sum of tow numbers.
a=1
b=2
sum=$[$a+$b]
echo "$a+$b=$sum"

        数学计算要用 [] 括起来并且外头要带一个 ‘$’ ,脚本结果为:

1
[root@192 sbin]# sh sum.sh

        下面为几个数学运算相关的例子:

        乘法运算:

1
[root@192 sbin]# sh 1.sh
1
2
3
4
5
#!/bin/bash
a=3
b=2
c=$[$a*$b]
echo $c

        除法运算:

1
[root@192 sbin]# vim 2.sh

        加入内容:

1
2
3
4
5
#!/bin/bash
a=10
b=3
c=$[$a/$b]
echo $c

        除法运算中 ,c 的结果为 3 ,并不是一个小数,这是因为 shell 默认是不支持小数的。如果想要看小数,需要借助于 bc ,bc 工具是 linux 系统里面的计算器,如果没有就先安装

1
[root@192 sbin]# yum install -y bc
1
2
[root@192 sbin]# echo "scale=2;10/3"|bc
3.33

和用户交互

        shell 脚本可以实现,让用户输入一些字符串或者让用户去选择的行为。

1
[root@192 sbin]# vim read.sh

        加入内容:

1
2
3
4
5
6
#!/bin/bash
#Using 'read' in shell script.
read -p "Please input a number:" x
read -p "Please input another number:" y
sum=$[$x+$y]
echo "The sum of the two numbers is:$sum"

        read 命令就是用在这样的地方,用于和用户交互。它把用户输入的字符串作为变量值。

        执行脚本

1
[root@192 sbin]# sh read.sh

        加上 -x 选项,再来看看这个执行过程:

1
[root@192 sbin]# sh -x read.sh

shell 脚本预设变量

        有时候会用到这样的命令 /etc/init.d/iptables restart 前面的 /etc/init.d/iptables 文件其实就是一个 shell 脚本,为什么后边可以跟一个 restart ,这里就涉及到了 shell 脚本的 预设变量。实际上, shell 脚本在执行的时候后边是可以跟参数的,而且还可以跟多个。

1
[root@192 sbin]# vim option.sh

        加入内容:

1
2
3
#!/bin/bash
sum=$[$1+$2]
echo "sum=$sum"

        执行结果为:

1
[root@192 sbin]# sh -x option.sh 1 2

        在脚本中,会觉得奇怪,哪里来的 $1 和 $2 。这就是 shell 脚本的预设变量,其中 $1 的值就是在执行的时候输入的 1 ,而 $2 的值就是在执行的时候输入的 $2 ,当然一个 shell 脚本的预设变量是没有限制的。另外,还有一个 $0 ,不过它代表的是脚本本身的名字。

        修改一下脚本:

1
[root@192 sbin]# vim option.sh

        写入内容:

1
2
#!/bin/bash
echo "$1 $2 $0"

        执行结果:

1
[root@192 sbin]# sh -x option.sh 1 2